{createAction} = require('redux-actions')
moment = require('moment')
_ = require('underscore')
actions =
  getGXInfoStart:createAction('GXLXSQ/GET_GXINFO_START')
  getGXINFOCompleted:createAction('GXLXSQ/GET_GXINFO_COMPLETED')
  postStart:createAction('GXLXSQ/POST_START')
  postCompleted:createAction('GXLXSQ/POST_COMPLETED')
  postFail:createAction('GXLXSQ/POST_FAIL')
  resetState:createAction('GXLXSQ/RESET_STATE')
  
  fetchGxInfo:(pilotCode)->
    (dispatch)->
      dispatch actions.getGXInfoStart()
      currDate = moment(new Date()).format('YYYY-MM-DD')
      fetch("http://202.136.214.163:801/PilotGxWh.ashx?pilotCode=#{pilotCode}&date=#{currDate}",{
          method: 'GET'
          mode: 'cors'
          cache: 'default'
          headers: { 'Content-Type':'application/x-www-form-urlencoded'}
          # body:"pageNum=#{pageNum}&state=1"
        })
      .then (res)->
        res.json()
      .then (json)->
        dispatch actions.getGXINFOCompleted
              YLXTS:json.YLXTS
              SYTS:json.SYTS
      .catch (err)->
        console.log(err)


  PostGxsq:(data)->
    (dispatch)->
      debugger
      dispatch actions.postStart()
      data.method = 'yhygxlxsq'
      postStr = ""
      for own k,v of data
        postStr += "#{k}=#{encodeURI(v)}&"
      if postStr.length>0
        postStr = postStr.slice 0,postStr.length-1
      fetch("http://202.136.214.163:801/PilotGxWh.ashx",{
          method: 'POST'
          mode: 'cors'
          cache: 'default'
          headers: { 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
          body:postStr
        })
      .then (res)->
        debugger
        if res.status is 200 and res.url.indexOf('Error.aspx') is -1
          dispatch actions.postCompleted()
        else if res.status is 500
          Promise.reject(res.text())
        else
          Promise.reject('服务器发生错误')
      .catch (err)->
        debugger
        if err.then
          err.then (txt)->
            dispatch actions.postFail new Error(txt)
        else
          dispatch actions.postFail new Error(err)
        # err.text().then (errMsg)->
        #   dispatch actions.postFail new Error(errMsg)

module.exports = actions
